<template>
  <div class="pro-dialog">
    <el-dialog
      v-model="dialogVisible"
      @open="onOpen"
      @close="onClose"
      title="活动编辑"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        size="default"
        label-width="100px"
      >
        <el-form-item label="活动类型" prop="proType">
          <el-select
            v-model="formData.proType"
            placeholder="请选择活动类型"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option
              v-for="item in proTypeOptions"
              :key="item.bannerType"
              :label="item.title"
              :value="item.bannerType"
            ></el-option>
          </el-select>
        </el-form-item>
        <template v-if="formData.proType">
          <el-form-item
            :label="labelConfig.name[formData.proType]"
            prop="proName"
          >
            <el-input
              v-model="formData.proName"
              placeholder="请输入活动名称"
              :maxlength="50"
              show-word-limit
              clearable
              prefix-icon="Cellphone"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
          <el-form-item label="可见范围" prop="isRange">
            <el-radio-group v-model="formData.isRange">
              <el-radio value="1">自己可见</el-radio>
              <el-radio value="2">本单位可见</el-radio>
              <el-radio value="3">互联网公开</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            :label="labelConfig.proTime[formData.proType]"
            prop="projectTime"
          >
            <el-date-picker
              type="datetimerange"
              v-model="formData.projectTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :style="{ width: '100%' }"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              range-separator="至"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="是否报名" prop="registrationType" required>
            <el-switch
              v-model="formData.registrationType"
              active-value="1"
              inactive-value="0"
            ></el-switch>
          </el-form-item>
          <el-form-item
            label="报名时限"
            prop="registrationTime"
            v-if="formData.registrationType == '1'"
            :rules="
              formData.registrationType === '0' ? rules.registrationTime : []
            "
          >
            <el-date-picker
              type="datetimerange"
              v-model="formData.registrationTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :style="{ width: '100%' }"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              range-separator="至"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item
            :label="labelConfig.text[formData.proType]"
            prop="title"
          >
            <!-- <editor
              class="WangEditor"
              @select="getRich"
              ref="childrenRef"
              :editValue="formData.title"
              v-if="dialogVisible"
            /> -->
            <editor v-model="formData.title" v-if="dialogVisible" />
          </el-form-item>
          <el-form-item
            :label="labelConfig.teacher[formData.proType]"
            prop="teachers"
          >
            <div v-for="item in formData.teacherList" :key="item.id">
              {{ item.username }},
            </div>
            <el-button @click="addTeacherShow"
              >添加{{ labelConfig.teacher[formData.proType] }}</el-button
            >
          </el-form-item>
          <el-form-item
            label="主办方"
            prop="chargePerson"
            v-if="formData.proType == 24 || formData.proType == 25"
          >
            <el-input
              v-model="formData.chargePerson"
              placeholder="请输入主办方"
              :maxlength="50"
              show-word-limit
              clearable
              prefix-icon="Cellphone"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="承办方"
            prop="contractor"
            v-if="formData.proType == 24"
          >
            <el-input
              v-model="formData.contractor"
              placeholder="请输入承办方"
              :maxlength="50"
              show-word-limit
              clearable
              prefix-icon="Cellphone"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="labelConfig.img[formData.proType]"
            prop="imgUrl"
            required
            style="margin-bottom: 0px"
          >
            <el-upload
              ref="imgUrl"
              v-model:file-list="imgUrlfileList"
              :action="imgUrlAction"
              :before-upload="imgUrlBeforeUpload"
              list-type="picture-card"
              accept="image/*"
              :limit="1"
              :on-success="handleUploadSuccess"
              :on-preview="handlePictureCardPreview"
              :headers="headers"
              :on-remove="handleRemove"
              :class="{ hide: hideUpload }"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <span class="file-tip">*图片大小为275*150</span>
          <el-form-item
            label="版头图"
            prop="bannerUrl"
            required
            style="margin-bottom: 0px"
          >
            <el-upload
              ref="bannerUrl"
              v-model:file-list="bannerUrlfileList"
              :action="imgUrlAction"
              :before-upload="bannerUrlBeforeUpload"
              list-type="picture-card"
              accept="image/*"
              :limit="1"
              :on-success="handleBannerUploadSuccess"
              :on-preview="handlePictureCardPreview"
              :headers="headers"
              :on-remove="handleRemoveBanner"
              :class="{ hide: hideBannerUpload }"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <span class="file-tip">*图片大小为1920*1080</span>
          <el-form-item label="相关附件" prop="fileList">
            <el-upload
              ref="fileListUpload"
              v-model:file-list="fileList"
              :action="imgUrlAction"
              multiple
              :before-upload="fileListBeforeUpload"
              :headers="headers"
              :on-success="handleUploadSuccessFile"
            >
              <el-button size="small" type="primary">+点击上传</el-button>
            </el-upload>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </template>
    </el-dialog>
    <MemberList
      v-model="memberDialogVisible"
      @confirm="addTeacher"
      :checkedList="formData.teacherList"
      type="role"
    ></MemberList>
    <el-dialog v-model="imgDialogVisible">
      <img class="w-full" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup>
import useActivityStore from "@/store/modules/activity";
import { getToken } from "@/utils/auth";
import { getProjectInfo } from "@/api/pms/project";
import MemberList from "./memberList.vue";

const headers = ref({
  Authorization: "Bearer " + getToken(),
});
const baseURL = import.meta.env.VITE_APP_BASE_API;
const { proxy } = getCurrentInstance();
const props = defineProps({
  currentProId: { type: String, default: "" },
});
const formRef = ref();
const ruleFormRef = ref();

const labelConfig = {
  name: {
    2: "课程名称",
    3: "实验名称",
    4: "项目名称",
    24: "竞赛名称",
    25: "成长营名称",
    26: "活动名称",
  },
  teacher: {
    2: "主讲人",
    3: "负责人",
    4: "负责人",
    24: "负责人",
    25: "负责人",
    26: "负责人",
  },
  text: {
    2: "课程介绍",
    3: "实验介绍",
    4: "项目介绍",
    24: "竞赛介绍",
    25: "研学特色",
    26: "活动介绍",
  },
  proTime: {
    2: "课程时间",
    3: "实验时间",
    4: "项目时间",
    24: "比赛时间",
    25: "研学时间",
    26: "活动时间",
  },
  img: {
    2: "课程封面",
    3: "实验封面",
    4: "项目封面",
    24: "比赛封面",
    25: "研学封面",
    26: "活动封面",
  },
};
const data = reactive({
  formData: {
    proName: "",
    proType: "",
    projectTime: null,
    registrationType: "1",
    registrationTime: null,
    title: undefined,
    imgUrl: null,
    bannerUrl: null,
    teacherList: [],
    isRange: "1",
    chargePerson: "",
    contractor: "",
  },
  rules: {
    proName: [
      {
        required: true,
        message: "请输入活动名称",
        trigger: "blur",
      },
    ],
    proType: [
      {
        required: true,
        message: "请选择活动类型",
        trigger: "change",
      },
    ],
    projectTime: [
      {
        required: true,
        message: "活动时限不能为空",
        trigger: "change",
      },
    ],
    bannerUrl: [
      {
        required: true,
        message: "版头图不能为空",
        trigger: "change",
      },
    ],
    imgUrl: [
      {
        required: true,
        message: "封面不能为空",
        trigger: "change",
      },
    ],
    registrationTime: [
      {
        required: true,
        message: "报名时限不能为空",
        trigger: "change",
      },
    ],
    title: [],
  },
});
const { formData, rules } = toRefs(data);
const proTypeOptions = ref([]);
const sponsor = ref(""); //主办方
const memberDialogVisible = ref(false);
const imgDialogVisible = ref(false);
const dialogImageUrl = ref("");
// 上传请求路径
const imgUrlAction = ref(import.meta.env.VITE_APP_BASEURL + "/common/upload");
// 上传文件列表
const imgUrlfileList = ref([]);
// 上传版头图文件列表
const bannerUrlfileList = ref([]);
// 上传文件列表
const fileList = ref([]);
const hideUpload = ref(false);
const limitCount = ref(1);
const hideBannerUpload = ref(false);
const limitBannerCount = ref(1);
/**
 * @name: 上传之前的文件判断
 * @description: 上传之前的文件判断，判断文件大小文件类型等
 * @param {*} file
 * @return {*}
 */
function imgUrlBeforeUpload(file) {
  let isRightSize = file.size / 1024 / 1024 < 2000;
  if (!isRightSize) {
    proxy.$modal.msgError("文件大小超过 2G");
  }
  let isAccept = new RegExp("image/*").test(file.type);
  if (!isAccept) {
    proxy.$modal.msgError("应该选择image/*类型的文件");
  }
  return isRightSize && isAccept;
}
function bannerUrlBeforeUpload(file) {
  let isRightSize = file.size / 1024 / 1024 < 2000;
  if (!isRightSize) {
    proxy.$modal.msgError("文件大小超过 2G");
  }
  let isAccept = new RegExp("image/*").test(file.type);
  if (!isAccept) {
    proxy.$modal.msgError("应该选择image/*类型的文件");
  }
  return isRightSize && isAccept;
}
function fileListBeforeUpload(file) {
  let isRightSize = file.size / 1024 / 1024 < 2000;
  if (!isRightSize) {
    proxy.$modal.msgError("文件大小超过 2G");
  }
  return isRightSize;
}
// 弹窗设置
const dialogVisible = defineModel();
// 弹窗确认回调
const emit = defineEmits(["confirm"]);
/**
 * @name: 弹窗打开后执行
 * @description: 弹窗打开后执行方法
 * @return {*}
 */
async function onOpen() {
  proTypeOptions.value = await useActivityStore().getType();
  if (props.currentProId) {
    getList();
  }
}
//修改时初始化
function getList() {
  getProjectInfo({ id: props.currentProId }).then((response) => {
    formData.value.proName = response.data.proName;
    formData.value.proType = response.data.proType;
    formData.value.isRange = response.data.isRange;
    formData.value.chargePerson = response.data.chargePerson;
    formData.value.contractor = response.data.contractor;
    formData.value.registrationType = response.data.registrationType;
    response.data.registrationType == "1"
      ? (formData.value.registrationTime = [
          response.data.registrationStartTime + " 00:00:00",
          response.data.registrationEndTime + " 00:00:00",
        ])
      : "";
    formData.value.projectTime = [
      response.data.startTime + " 00:00:00",
      response.data.endTime + " 00:00:00",
    ];
    formData.value.sort = response.data.sort;
    formData.value.teacherList = JSON.parse(
      JSON.stringify(response.data.teacherList)
    );
    formData.value.title = response.data.title;
    formData.value.imgUrl = response.data.url;
    imgUrlfileList.value.push({
      name: "封面",
      url: response.data.url,
    });
    hideUpload.value = imgUrlfileList.value.length >= limitCount.value;
    formData.value.bannerUrl = response.data.banner;
    bannerUrlfileList.value.push({
      name: "版头图",
      url: response.data.banner,
    });
    hideBannerUpload.value =
      bannerUrlfileList.value.length >= limitBannerCount.value;
    if (response.data.informations && response.data.informations.length) {
      fileList.value = response.data.informations.map((item) => {
        let i = {
          name: item.name,
          response: {
            url: item.url,
            fullurl: item.fullurl,
            name: item.name,
          },
        };
        return i;
      });
    }
  });
}
/**
 * @name: 弹窗关闭时执行
 * @description: 弹窗关闭方法，重置表单
 * @return {*}
 */
function onClose() {
  formRef.value.resetFields();
  formData.value = {
    proName: "",
    proType: "",
    projectTime: null,
    registrationType: "1",
    registrationTime: null,
    title: "",
    imgUrl: "",
    bannerUrl: "",
    teacherList: [],
    isRange: "1",
    chargePerson: "",
    contractor: "",
  };
  imgUrlfileList.value = [];
  bannerUrlfileList.value = [];
  fileList.value = [];
  sponsor.value = "";
  hideBannerUpload.value = false;
  hideUpload.value = false;
}
/**
 * @name: 弹窗取消
 * @description: 弹窗取消方法
 * @return {*}
 */
function close() {
  dialogVisible.value = false;
}

// 添加教师弹窗打开
function addTeacherShow() {
  memberDialogVisible.value = true;
}
// 添加教师
function addTeacher(params) {
  formData.value.teacherList = params.map((item) => {
    let i = {
      id: item.id,
      username: item.username,
    };
    return i;
  });
}
//滚动错误项
function moveToErr() {
  nextTick(() => {
    let isError = document.getElementsByClassName("is-error");
    if (isError.length) {
      isError[0].scrollIntoView({
        block: "center",
        behavior: "smooth",
      });
    }
  });
}
/**
 * @name: 弹窗表单提交
 * @description: 弹窗表单提交方法
 * @return {*}
 */
function handelConfirm() {
  proxy.$modal
    .confirm("活动创建或修改信息后，前台活动暂不显示，需提交审核后显示。")
    .then(function () {
      formRef.value.validate((valid) => {
        if (!valid) {
          moveToErr();
          return;
        }
        // TODO 提交表单
        if (!formData.value.proName.trim()) {
          proxy.$modal.msgError("活动名称不能为全空格");
          return false;
        }
        if (
          formData.value.registrationType == "1" &&
          !formData.value.registrationTime
        ) {
          proxy.$modal.msgError("请填写报名时间");
          return false;
        }
        let params = {
          proName: formData.value.proName,
          isRange: formData.value.isRange,
          proType: formData.value.proType,
          chargePerson: formData.value.chargePerson,
          contractor: formData.value.contractor,
          registrationType: formData.value.registrationType,
          registrationStartTime:
            formData.value.registrationType == "1"
              ? formData.value.registrationTime[0]
              : "",
          registrationEndTime:
            formData.value.registrationType == "1"
              ? formData.value.registrationTime[1]
              : "",
          startTime: formData.value.projectTime[0],
          endTime: formData.value.projectTime[1],
          teacherList: JSON.parse(JSON.stringify(formData.value.teacherList)),
          url: formData.value.imgUrl,
          banner: formData.value.bannerUrl,
          title: formData.value.title.replace(/\n/g, ""),
          id: props.currentProId ? props.currentProId : "",
          informations: [],
        };
        params.informations = fileList.value.map((item) => {
          let i = {
            url: item.response.url,
            fullurl: item.response.fullurl,
            name: item.response.name,
          };
          return i;
        });
        // 回调父级组件
        emit("confirm", params);
        // close();
      });
    })
    .catch(() => {});
}
function handleUploadSuccess(res) {
  if (res) {
    formData.value.imgUrl = res.fullurl;
    hideUpload.value = imgUrlfileList.value.length >= limitCount.value;
  }
}
function handleUploadSuccessFile(res) {}
function handleBannerUploadSuccess(res) {
  if (res) {
    formData.value.bannerUrl = res.fullurl;
    hideBannerUpload.value =
      bannerUrlfileList.value.length >= limitBannerCount.value;
  }
}
//当编辑器的内容更新时，获取该值
const getRich = function (value) {
  formData.value.title = value;
};

//图片放大
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  imgDialogVisible.value = true;
};
//缩略图删除
const handleRemove = (res) => {
  formData.value.imgUrl = "";
  hideUpload.value = imgUrlfileList.value.length >= limitCount.value;
};
//版头图图片删除
const handleRemoveBanner = (res) => {
  formData.value.bannerUrl = "";
  hideBannerUpload.value =
    bannerUrlfileList.value.length >= limitBannerCount.value;
};
</script>
<style lang="scss">
.el-upload__tip {
  line-height: 1.2;
}
.file-tip {
  padding-left: 100px;
  color: red;
  margin-bottom: 5px;
  margin-top: 12px;
  display: inline-block;
}
.pro-dialog {
  .el-dialog {
    width: 80%;
    .el-dialog__body {
      height: 70vh;
      overflow-y: auto;
      .el-form {
        width: 90%;
        .el-tag {
          margin-right: 10px;
        }
        .check-list {
          padding: 10px;
          &:nth-child(even) {
            background: rgba(64, 158, 255, 0.2);
          }
        }
      }
    }
  }
}
</style>
